package algorithm.leetcode.medium;

/*
 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数，也可以是另一个逆波兰表达式。
 */

import java.util.Stack;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/11/27
 */
public class Question150 {

    public static void main(String[] args) {
        Question150 question = new Question150();
        String[] tokens = {"4", "3", "-"};
        int sum = question.evalRPN(tokens);
        System.out.println(sum);
    }

    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int num1, num2;
        for (String item : tokens) {
            switch (item) {
                case "+":
                    num2 = stack.pop();
                    num1 = stack.pop();
                    stack.push(num1 + num2);
                    break;
                case "-":
                    num2 = stack.pop();
                    num1 = stack.pop();
                    stack.push(num1 - num2);
                    break;
                case "*":
                    num2 = stack.pop();
                    num1 = stack.pop();
                    stack.push(num1 * num2);
                    break;
                case "/":
                    num2 = stack.pop();
                    num1 = stack.pop();
                    stack.push(num1 / num2);
                    break;
                default:
                    stack.push(Integer.parseInt(item));
            }
        }
        return stack.pop();
    }
}
